package com.px.baolaiapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.px.common.api.CommonPage;
import com.px.common.constant.Constant;
import com.px.mbg.mapper.DeliverGoodMapper;
import com.px.mbg.model.*;
import com.px.baolaiapi.dto.DeliverGoodDto;
import com.px.baolaiapi.dto.DeliverGoodSaleItmeDto;
import com.px.baolaiapi.page.DeliverGoodPage;
import com.px.baolaiapi.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 发货表 服务实现类
 * </p>
 *
 * @author 品讯科技
 * @since 2022-02-11
 */
@Service
public class DeliverGoodServiceImpl extends ServiceImpl<DeliverGoodMapper, DeliverGood> implements IDeliverGoodService {
    @Autowired
    private IGoodtypeService goodtypeService;

    @Autowired
    private IUnitService unitService;

    @Autowired
    private IStorageService storageService;

    @Autowired
    private ISaleOrderService saleOrderService;

    @Autowired
    private ISaleOrderItemService saleOrderItemService;
    @Autowired
    private IUsersService usersService;
    @Autowired
    private IRetreatGoodService retreatGoodService;
    @Autowired
    private IWhOfStorageLocationService whOfStorageLocationService;
    @Autowired
    private IToDoListService toDoListService;



   /* @Autowired
    private IWarehouseService warehouseService;*/

    /**
     * 添加发货记录
     *
     * @param deliverGood deliverGood
     * @return {@link int}
     */
    @Override
    public int add(List<DeliverGood> deliverGood) {
        //销售订单号
        final String DeliverNo = sequenceNo(Constant.BH_NO.FH_NO, "yyyyMMdd", 4);
        //批次号
        //查询销售订单单据编号
        //
        SaleOrder byId = saleOrderService.getById(deliverGood.get(0).getSaleOrderId());
        final String DeliverBatch = sequenceBatch(byId.getBnoNo(), 4);
        for (DeliverGood good : deliverGood) {
            // i==-1 小于0  i==0 等于0 i==1 大于 0
            int i=good.getNumber().compareTo(BigDecimal.ZERO);
            if(i==1) {
                good.setBatchNumber(DeliverBatch);
                good.setSaleOrderNumber(DeliverNo);
                this.save(good);
                // 出库
//                SaleOrderItem saleOrderItem = saleOrderItemService.getById(good.getSaleOrderItemId());
//                WhChangeDto whChangeDto = new WhChangeDto();
//                whChangeDto.setStorageId(good.getStorageId());
//                whChangeDto.setStorageLocationCode(good.getStorageLocationCode());
//                whChangeDto.setWhCode(saleOrderItem.getPartNumber());
//                whChangeDto.setWhName(saleOrderItem.getPartNumberName());
//                whChangeDto.setCount(good.getNumber());
//                whChangeDto.setReqNo(good.getSaleOrderNumber());
//                whChangeDto.setReceiptsType(ReceiptsTypeEnum.XSCH.getValue());
//                whOfStorageLocationService.takeOutStorage(whChangeDto);
            }
        }

        // 添加待办任务记录
//        toDoListService.addToDoList(byId.getId(), byId.getBnoNo(), ReceiptsTypeEnum.XSCH);

        return 1;
    }
    /**
     *
     * @param no   编码
     *
     * @param num 后尾数数值
     * @return
     */
    public String sequenceBatch(String no, Integer num) {
        //取日期格式
        LocalDateTime now = LocalDateTime.now();

        //截取数值  no + format
        Integer subInt = no.length();
        //查询编号
        LambdaQueryWrapper<DeliverGood> wrapper = Wrappers.lambdaQuery();
        //时间倒序
        wrapper.orderByDesc(DeliverGood::getCreatedTime);
        wrapper.like(DeliverGood::getBatchNumber,no+"%");
        //查询like拼后值并倒序
        List<DeliverGood> list = this.list(wrapper);
        //组成后的编码
        String sequenceNoLast = null;
        //最后末尾序列位数值
        String sequ = null;
        if (CollectionUtils.isEmpty(list)) {
            //首次编码生成
            sequ = String.format("%0"+num+"d", 1);
            sequenceNoLast = no  + sequ;
        } else {
            String sequenceNo = list.get(0).getBatchNumber();
            Integer integer = new Integer(sequenceNo.substring(subInt));
            integer++;
            sequ = String.format("%0"+num+"d", integer);
            sequenceNoLast = no + sequ;
        }
        //返回最后组成的编码
        return sequenceNoLast;
    }



    /**
     *
     * @param no   编码首拼
     * @param formatDate  日期格式
     * @param num 后尾数数值
     * @return
     */
    public String sequenceNo(String no, String formatDate, Integer num) {
        //取日期格式
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(formatDate));
        //截取数值  no + format
        Integer subInt = no.length() + format.length();
        //查询编号
        LambdaQueryWrapper<DeliverGood> wrapper = Wrappers.lambdaQuery();
        //时间倒序
        wrapper.orderByDesc(DeliverGood::getCreatedTime);
        wrapper.like(DeliverGood::getSaleOrderNumber,no + format + "%");
        //查询like拼后值并倒序
        List<DeliverGood> list = this.list(wrapper);
        //组成后的编码
        String sequenceNoLast = null;
        //最后末尾序列位数值
        String sequ = null;
        if (CollectionUtils.isEmpty(list)) {
            //首次编码生成
            sequ = format + String.format("%0"+num+"d", 1);
            sequenceNoLast = no  + sequ;
        } else {
            String sequenceNo = list.get(0).getSaleOrderNumber();
            Integer integer = new Integer(sequenceNo.substring(subInt));
            integer++;
            sequ = format + String.format("%0"+num+"d", integer);
            sequenceNoLast = no + sequ;
        }
        //返回最后组成的编码
        return sequenceNoLast;
    }
    /**
     * 变更
     *
     * @param deliverGood deliverGood
     * @return {@link int}
     */
    @Override
    public int update(DeliverGood deliverGood) {
        DeliverGood deliverGood1 = this.queryById(deliverGood.getId());
        BeanUtil.copyProperties(deliverGood,deliverGood1);
        if (this.updateById(deliverGood1)) {
            return 1;
        }
        return 0;
    }

    /**
     * 通过id查询查询
     *
     * @param id id
     * @return {@link Goodtype}
     */
    @Override
    public DeliverGood  queryById(Long id) {
        return this.getById(id);
    }

    /**
     * 通过code查询
     *
     * @param code code
     * @return {@link Goodtype}
     */
    @Override
    public DeliverGood queryByCode(String code) {
        LambdaQueryWrapper<DeliverGood> wrapper = Wrappers.lambdaQuery();
        List<DeliverGood> list = this.list(wrapper);
        return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return {@link }
     */
    @Override
    public boolean deleteById(Long id) {
        DeliverGood deliverGood = this.queryById(id);
        if (ObjectUtil.isNotEmpty(deliverGood)) {
            deliverGood.setIsDelFlag(Constant.IS_ENABLED.DISABLED);
            return this.updateById(deliverGood);
        }
        return false;
    }

    /**
     * 查询类型列表
     *
     * @return {@link List <DeliverGoodSaleItmeDto>}
     */
    @Override
    public List<DeliverGoodSaleItmeDto> querySelect(String saleOrderNumber, String batchNumber) {
        LambdaQueryWrapper<DeliverGood> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(DeliverGood::getSaleOrderNumber,saleOrderNumber);
        if(StringUtils.isNotEmpty(batchNumber)) {
            wrapper.eq(DeliverGood::getBatchNumber, batchNumber);
        }
        List<DeliverGood> list = this.list(wrapper);
        List<DeliverGoodSaleItmeDto> deliverGoodSaleItmeDtoList = new ArrayList<>();
        DeliverGoodSaleItmeDto deliverGoodSaleItmeDto = null ;
        for (DeliverGood deliverGood : list) {
            deliverGoodSaleItmeDto = new DeliverGoodSaleItmeDto();
            BeanUtil.copyProperties(deliverGood,deliverGoodSaleItmeDto);
            deliverGoodSaleItmeDto.setShippedNum(deliverGood.getNumber());

            // 库房名称
            Storage storage = storageService.getById(deliverGood.getStorageId());
            deliverGoodSaleItmeDto.setStorageName(storage.getName());

            //查询销售订单明细信息
            SaleOrderItem saleOrderItem = saleOrderItemService.getById(deliverGood.getSaleOrderItemId());
            BeanUtil.copyProperties(saleOrderItem,deliverGoodSaleItmeDto);
            //出货数
            deliverGoodSaleItmeDto.setReturnNum(new BigDecimal(0));
            LambdaQueryWrapper<RetreatGood> retreatGoodLambdaQueryWrapper = Wrappers.lambdaQuery(RetreatGood.class);
            retreatGoodLambdaQueryWrapper.eq(RetreatGood::getSaleOrderId,saleOrderItem.getSaleOrderId());
            retreatGoodLambdaQueryWrapper.eq(RetreatGood::getSaleOrderItemId,saleOrderItem.getId());
            retreatGoodLambdaQueryWrapper.eq(RetreatGood::getSaleOrderNumber,deliverGood.getSaleOrderNumber() );
            if(StringUtils.isNotEmpty(batchNumber)) {
                retreatGoodLambdaQueryWrapper.eq(RetreatGood::getBatchNumber, batchNumber);
            }
            List<RetreatGood> list2 = retreatGoodService.list(retreatGoodLambdaQueryWrapper);
            if (!CollectionUtil.isEmpty(list2)) {
                //求和
                BigDecimal returnNum = new BigDecimal(0);
                for (RetreatGood retreatGood : list2) {
                    returnNum = returnNum.add(retreatGood.getNumber());
                }
                deliverGoodSaleItmeDto.setReturnNum(returnNum);
            }
            deliverGoodSaleItmeDtoList.add(deliverGoodSaleItmeDto);


        }

        return deliverGoodSaleItmeDtoList;
    }

    @Override
    public List<DeliverGood> queryNumberSelect(String saleOrderNumber) {
        QueryWrapper<DeliverGood> wrapper = new QueryWrapper<>();
        wrapper.select(" DISTINCT sale_order_number ").lambda();
        if(StringUtils.isNotEmpty(saleOrderNumber)) {
            wrapper.like("sale_order_number", saleOrderNumber);
        }
        return this.list(wrapper);
    }

    /**
     * 分页查询类型
     *
     * @param deliverGoodPage 公共领域页面
     * @return {@link CommonPage}
     */
    @Override
    public CommonPage queryPage(DeliverGoodPage deliverGoodPage) {
        QueryWrapper<DeliverGood> wrapper = new QueryWrapper<>();
        wrapper.select(" sum(number) as number, sale_order_number,created_time,created_by,sale_order_id,batch_number").lambda();
        wrapper.orderByDesc("created_time ");
        wrapper.groupBy("sale_order_number,created_time,created_by,sale_order_id,batch_number");
        if (deliverGoodPage.getSaleOrderId() != null && deliverGoodPage.getSaleOrderId() > 0) {
            wrapper.eq("sale_order_id", deliverGoodPage.getSaleOrderId());
        }

        if (StringUtils.isNotEmpty(deliverGoodPage.getSaleOrderNumber()) ) {
            wrapper.like("sale_order_number", "%" + deliverGoodPage.getSaleOrderNumber() + "%");
        }
        String startDate = deliverGoodPage.getStartDate();
        if (StringUtils.isNotEmpty(startDate)) {
            wrapper.ge("DATE_FORMAT(created_time,'%Y-%m-%d')", startDate);
        }
        String endDate = deliverGoodPage.getEndDate();
        if (StringUtils.isNotEmpty(endDate)) {
            wrapper.le("DATE_FORMAT(created_time,'%Y-%m-%d')", endDate);
        }
        List<DeliverGood> list = this.list(wrapper);
        Page<DeliverGood> page = this.page(new Page<>(deliverGoodPage.getPageNum(), deliverGoodPage.getPageRow()), wrapper);
        CommonPage restPage = CommonPage.restPage(page);
        List<DeliverGoodDto> deliverGoodDtoList = new ArrayList<>();
        List<DeliverGood> records = page.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            records.forEach(deliverGood -> {

                DeliverGoodDto deliverGoodDto = new DeliverGoodDto();
                BeanUtil.copyProperties(deliverGood,deliverGoodDto);
                //销售订单表的单号
                SaleOrder saleOrder = saleOrderService.getById(deliverGood.getSaleOrderId());
                if (ObjectUtil.isNotEmpty(saleOrder)) {
                    deliverGoodDto.setBnoNo(saleOrder.getBnoNo());
                }
                //查询订单明细
                SaleOrderItem saleOrderItem = saleOrderItemService.getById(deliverGood.getSaleOrderItemId());
                if (ObjectUtil.isNotEmpty(saleOrderItem)) {
                    deliverGoodDto.setPartNumber(saleOrderItem.getPartNumber());
                    deliverGoodDto.setPartNumberName(saleOrderItem.getPartNumberName());
                }
                //通过创建人账号查询名称
                Users users = usersService.queryUserByAccount(deliverGood.getCreatedBy());
                if (ObjectUtil.isNotEmpty(users)) {
                    deliverGoodDto.setUserName(users.getUsername());
                }

                deliverGoodDtoList.add(deliverGoodDto);
            });
            restPage.setList(deliverGoodDtoList);
        }
        return restPage;

    }

}
